package redora.rdo.client.model;


import com.google.gwt.core.client.GWT;
import com.google.gwt.http.client.Request;
import com.google.gwt.http.client.RequestBuilder;
import com.google.gwt.http.client.RequestCallback;
import com.google.gwt.http.client.RequestException;
import com.google.gwt.http.client.Response;
import com.google.gwt.http.client.URL;
import com.google.gwt.json.client.JSONArray;
import com.google.gwt.json.client.JSONParser;
import com.smartgwt.client.types.Side;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.layout.VLayout;
import com.smartgwt.client.widgets.tab.Tab;
import com.smartgwt.client.widgets.tab.TabSet;

public class ModelPanel extends VLayout {
	boolean isInit = false;

	public ModelPanel() {
		init();
	}

	public void init() {
		if (!isInit) {
			// the vertical main panel style to set
			this.setWidth100();
			this.setHeight100();
			this.setLayoutMargin(5);
			this.setStyleName("tabSetContainer");

			final TabSet modelTabs = new TabSet();
			modelTabs.setTabBarPosition(Side.LEFT);
			modelTabs.setTabBarAlign(Side.TOP);
			modelTabs.setHeight100();
			modelTabs.setTabBarThickness(100);

			initModelTab(modelTabs);

			this.addMember(modelTabs);
			this.draw();
			isInit = true;
		}
	}

	private void initModelTab(final TabSet modelTabs) {
		String url = URL.encode(GWT.getModuleBaseURL()
				+ "modelFieldsView.do?action=modelView");

		RequestBuilder builder = new RequestBuilder(RequestBuilder.GET, url);
		builder.setCallback(new RequestCallback() {
			public void onError(Request request, Throwable exception) {
				SC.say("getModels failed!");
			}

			public void onResponseReceived(Request request, Response response) {
				JSONArray models = JSONParser.parse(response.getText())
						.isArray();
				for (int i = 0; i < models.size(); i++) {
					String objectName = models.get(i).isObject().get(
							"objectName").toString().replaceAll("\"", "");
					Tab tab = new Tab(objectName);
					tab.setPane(new AttributesListCanvas(objectName));
					modelTabs.addTab(tab);
				}
			}
		});
		try {
			builder.send();
		} catch (RequestException e) {
			e.printStackTrace();
		}
	}
}
